//
//  XJYouMingTangViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/5/11.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJYouMingTangViewController.h"
#import "XJYMTSearchViewController.h"
#import "XJYMTTeiZiDetailViewController.h" // 详情

// View
#import "XJYMTTableViewCell.h"
#import "RBNoDataView.h" // 无数据占位图
#import "RBRefreshHeader.h"
#import "RBRefreshFooter.h"



// Model
#import "XJYMTModel.h"

static NSString *const XJYMTCellId = @"XJYMTCellId";

@interface XJYouMingTangViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic, strong) UITableView *tableView;

@property(nonatomic, strong) NSMutableArray *dataArray;
@property(nonatomic, strong) RBNoDataView *noDataView;


/**下拉刷新 页数*/
@property (nonatomic, assign) NSInteger page;

@end

@implementation XJYouMingTangViewController

#pragma mark - 一 lazy load
- (UITableView *)tableView {
    // 哥呀 !取反啊
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:(UITableViewStylePlain)];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
//        _tableView.backgroundColor = [UIColor lightGrayColor];
        
        // 注册cell
        [_tableView registerClass:[XJYMTTableViewCell class] forCellReuseIdentifier:XJYMTCellId];
        _tableView.tableFooterView = [UIView new];
    }
    return _tableView;
}

- (NSMutableArray *)dataArray {
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (RBNoDataView *)noDataView{
    if (!_noDataView) {
        _noDataView = [[RBNoDataView alloc] init];
    }
    return _noDataView;
}



#pragma mark - 二 视图生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor greenColor];
    
    [self configSelfViewAndNav];
    
    [self setupTableView];
    
    [self setupRefresh];
    
    self.page = 1;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // 显示导航条
    [self.navigationController setNavigationBarHidden:NO animated:YES];

}
#pragma mark - 三 UI
- (void)setupRefresh {
    
    // 下拉刷新
    RBRefreshHeader *mj_header = [RBRefreshHeader headerWithRefreshingTarget:self refreshingAction:@selector(requestYMTList)];
    self.tableView.mj_header = mj_header;
    [self.tableView.mj_header beginRefreshing];
    
    
    // 上拉加载更多
    RBRefreshFooter *mj_footer = [RBRefreshFooter footerWithRefreshingTarget:self refreshingAction:@selector(reloadMoreTopics)];
    self.tableView.mj_footer = mj_footer;
}
- (void)configSelfViewAndNav {
    // 标题
    self.navTitle = @"有名堂";

    // 配置 控制器自己的view
    self.edgesForExtendedLayout = UIRectEdgeNone; // 正真起作用的是这句话。
    self.extendedLayoutIncludesOpaqueBars = NO;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // 设置左边导航按钮
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(rightSearchBarAction:)];
    
}
- (void)rightSearchBarAction:(UIBarButtonItem *)btnItem {
    XJLog(@"");
    [JRToast showWithText:@"点击🔍"];
    
    XJYMTSearchViewController *ymtSearVC = [[XJYMTSearchViewController alloc] init];
    
    [self.navigationController pushViewController:ymtSearVC animated:YES];
}

- (void)setupTableView {
    
    //问题1:顶部紧挨着屏幕顶部self.edgesForExtendedLayout = UIRectEdgeNone; // 正真起作用的是这句话。
    //问题2:底部一部分cell被盖住 状态栏20，导航栏44，tabbar栏49
    self.tableView.frame = CGRectMake(0, 0, KWidth, KHeight- 64 - 49);

    [self.view addSubview:self.tableView];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    XJYMTTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:XJYMTCellId];
    
    XJYMTModel *model = self.dataArray[indexPath.row];
    
    [cell configureYMTCellWithAvator:model.avatar time:model.publish_time name:model.publish_name title:model.title content:model.content clickCount:model.click_count];
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 150;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    XJYMTTeiZiDetailViewController *tieziDetailVC = [[XJYMTTeiZiDetailViewController alloc] init];
    
    
    XJYMTModel *model = self.dataArray[indexPath.row];
    tieziDetailVC.navigationItem.title = model.title;
    
    tieziDetailVC.tieZiId = model.tieZiId;
    tieziDetailVC.type = @"ymt";
    
    [self.navigationController pushViewController:tieziDetailVC animated:YES];
}

#pragma mark - 五 - 网路请求
- (void)requestYMTList{
    
    // 下拉刷新的时候 加载页数重新设置为1
    self.page = 1;
    [self.tableView.mj_footer endRefreshing];
    
    // 取出重复数据
    if (self.dataArray.count) {
        [self.dataArray removeAllObjects];
    }
    
    NSDictionary *parDic = @{@"page":@"1",
                             @"invitation_type":@"ymt",
                             };
    [XJHttpTool requestInvitationListWithDic:parDic succesH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            NSArray *listArr = responseObjc[@"data"][@"list"];
            for (NSDictionary *dic in listArr) {
                XJYMTModel *ymtM = [XJYMTModel mj_objectWithKeyValues:dic];
                [self.dataArray addObject:ymtM];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];
                
                if (self.dataArray.count == 0) {
                    [self.noDataView rb_showNoDataViewInView:self.view message:@"没有数据" placeHolder:nil];
                }else {
                    [self.noDataView rb_hideNoDataView];
                }
            });
            
        }else{
            [JRToast showWithText:responseObjc[@"data"]];
        }
        
        [self.tableView.mj_header endRefreshing];
        
    } failH:^(NSError *error) {
        [JRToast showWithText:[error localizedDescription]];
        
        [self.tableView.mj_header endRefreshing];

    }];
}

- (void)reloadMoreTopics{
    
    [self.tableView.mj_header endRefreshing];
    
    self.page++;
    XJLog(@"页数:%@",[NSString stringWithFormat:@"%ld",self.page]);
    
    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    [parDic setValue:[NSString stringWithFormat:@"%ld",self.page] forKey:@"page"];
    [parDic setValue:@"ymt" forKey:@"invitation_type"];
    
    [XJHttpTool requestInvitationListWithDic:parDic succesH:^(id responseObjc) {
        
        NSData *jonsData = [NSJSONSerialization dataWithJSONObject:responseObjc options:NSJSONWritingPrettyPrinted error:nil];
        NSString *jsonStr = [[NSString alloc] initWithData:jonsData encoding:NSUTF8StringEncoding];
        XJLog(@"===:%@",jsonStr);
        
    
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSArray *tempArr = responseObjc[@"data"][@"list"];
            if (tempArr.count == 0) {
                [self.tableView.mj_footer endRefreshingWithNoMoreData];
            }else {
                [self.dataArray addObjectsFromArray:tempArr];
                
                [self.tableView.mj_footer endRefreshing];
            }
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
        [self.tableView.mj_footer endRefreshing];
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
